﻿using CBS.APP;
using CBS.Common.Office;
using CBS.DB.CBSEntity;
using CBS.Model.ManageModel;
using CBS.Model.UIModel;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CBS.Desktop.FormPage
{
    /// <summary>
    /// ImportStudentSignUpInfo.xaml 的交互逻辑
    /// </summary>
    public partial class ImportStudentSignUpInfo : Window
    {
        public ImportStudentSignUpInfo()
        {
            InitializeComponent();

            BindSemester();
        }

        private async void BindSemester()
        {
            try
            {
                var list = await Task.Run(() => SemesterApp.GetSelectList());

                if (list.Count == 0) return;

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;
                }));
                    cb_Semester.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async void BindCoursePlan()
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                var list = await Task.Run(() => CoursePlanApp.GetFullDataSelectList(semesterId));

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_CoursePlan.ItemsSource = list;
                }));
                    cb_CoursePlan.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void cb_Semester_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            BindCoursePlan();
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 指定要打开的Excel文件路径
                string filePath = $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\\CourseBillingSystem\\ExcelTemplate\\学生报道导入模板.xlsx";
                var pathArray = filePath.Split('.');
                filePath = $"{pathArray[0]}-{((CoursePlanSelectModel)cb_CoursePlan.SelectedItem).CoursePlanName}-{new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()}.{pathArray[1]}"; 
                string config = Properties.Settings.Default["StudentSignUpField"].ToString();
                List<ImportField> fields = JsonSerializer.Deserialize<List<ImportField>>(config);

                //List<int> selectColumnIndex = new List<int> { 10 };
                //List<List<string>> selectItems = new List<List<string>> { new List<string> { "否", "是" } };
                //int selectRowTotal = 40;
                //ExcelHelper.GetImportTemplate(filePath, fields, selectColumnIndex, selectItems, selectRowTotal);

                ExcelHelper.GetImportTemplate(filePath, fields);

                // 创建ProcessStartInfo实例，并配置要启动的程序和参数
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "EXCEL.EXE", // 或者使用完整路径，比如"C:\\Program Files\\Microsoft Office\\root\\Office16\\EXCEL.EXE"
                    Arguments = $"\"{filePath}\"",
                    UseShellExecute = true // 在.NET Core或.NET 5/6中需要设置为true来正常使用
                };

                Process process = new Process { StartInfo = startInfo };
                process.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int coursePlanId = ((CoursePlanSelectModel)cb_CoursePlan.SelectedItem).CoursePlanId;
                bool result = StudentSignUpApp.ImportStudentSignUp(semesterId, coursePlanId, tb_ChooseFile.Text, out string msg);
                if (result)
                {
                    this.DialogResult = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void btn_ChooseFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FileDialog dlg = new OpenFileDialog
                {
                    Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx",
                    InitialDirectory = $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\\CourseBillingSystem\\ExcelTemplate"
                };
                var result = dlg.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    tb_ChooseFile.Text = dlg.FileName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
    }
}
